import { login, getUsers, usertList } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userlist: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERS: (state, list) => {
    state.userlist = list
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username, password }).then(res => {
        const { access_token: token, success }  = res
        if(success){
          // 存储在cookie和vuex中
          commit('SET_TOKEN', token)
          setToken(token)
        }
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取个人信息
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUsers().then(res => {
        // 将头像和用户名存储在 vuex 中
        const { avatar, username } = res.data
        if(res.code !== 4101) {
          commit('SET_NAME', username)
          commit('SET_AVATAR', avatar)
        }else {
          removeToken()
          commit('RESET_STATE')
        }
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 清除 token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  },

  // 获取用户列表
  getUserList({ commit }, params)  {
    return new Promise(async (resolve, reject) => {
      const data = await usertList(params)
      resolve(data)
    }).catch(error => {
      reject(error)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

